/*
 *    远景插件
 * @author FurtherBank
 * @version 1.1
 */
cc.Class({
    extends: cc.Component,

    properties: {
        camera:  {
            default: null,
            tooltip: "远景所使用的相机节点。当此项为空则自动设置为画面下的 Main Camera",
            type: cc.Node,
        },
        parallax: {
            default: true,
            tooltip: "图片是否使用远景模式，注意设置好Sprite渲染方式为Tiled"
        },
        moveSpeed:  {
            visible () {
                return this.parallax;
            },
            default: new cc.Vec2(0,0),
            tooltip: "远景图片移动速度，注意非远景模式无法设置移动",
        },
        cameraRatio:  {
            default: new cc.Vec2(0,0),
            tooltip: "图片随相机移动位移比，0为紧贴相机，1为紧贴屏幕",
        },
        rotate: {
            default: false,
            tooltip: "图片是否自主旋转"
        },
        rotationSpeed: {
            visible () {
                return this.rotate;
            },
            default: 0,
            tooltip: "旋转速度,大于0逆时针"
        },
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        this.oriSize = new cc.Vec2(this.node.width, this.node.height);
        this.winSize = cc.winSize;
        // 照相机未选择时自动寻找MainCamera
        if (!this.camera) this.camera = cc.find('Canvas/Main Camera');
        this.cameraOffset = cc.Vec2.ZERO;
        this.cameraFloat = cc.Vec2.ZERO;
        // 远景：自动放大图片，使其遮盖屏幕
        if (this.parallax) {
            this.frames = new cc.Vec2(Math.ceil(this.winSize.width / this.oriSize.x) + 1, Math.ceil(this.winSize.height / this.oriSize.y) + 1);
            this.node.height = this.oriSize.y * this.frames.y;
            this.node.width = this.oriSize.x * this.frames.x;
        }

    },

    start () {

    },

    update (dt) {
        // 移动动作
        let cameraPos = this.camera.position.subtract(this.cameraOffset);
        this.cameraOffset = this.camera.position.clone();
        this.node.x += this.moveSpeed.x * dt + cameraPos.x * this.cameraRatio.x;
        this.node.y += this.moveSpeed.y * dt + cameraPos.y * this.cameraRatio.y;
        if (this.parallax) {
            if (this.camera.x + this.winSize.width / 2 > this.node.x + this.node.width / 2) {
                // 远景太靠左，右边快没了
                this.node.x += this.node.width / this.frames.x;
            } else if (this.camera.x - this.winSize.width / 2 < this.node.x-this.node.width / 2) {
                // 远景太靠右，左边快没了
                this.node.x -= this.node.width / this.frames.x;
            }
            if (this.camera.y + this.winSize.height / 2 > this.node.y + this.node.height / 2) {
                // 远景太靠下，上边快没了
                this.node.y += this.node.height / this.frames.y;
            } else if (this.camera.y-this.winSize.height / 2 < this.node.y-this.node.height / 2) {
                // 远景太靠上，下边快没了
                this.node.y -= this.node.height / this.frames.y;
            }
        }
        // 旋转动作
        if (this.rotate) {
            this.node.angle += dt * this.rotationSpeed;
        }
    },
});
